use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use std::any::Any;
use std::time::{Duration, Instant};

/// 内存池配置
#[derive(Debug, Clone)]
pub struct MemoryPoolConfig {
    /// 池中保留的最大对象数量
    pub max_pool_size: usize,
    /// 对象在池中的最长生存时间（秒）
    pub max_idle_time_secs: u64,
    /// 是否启用内存池
    pub enabled: bool,
}

impl Default for MemoryPoolConfig {
    fn default() -> Self {
        Self {
            max_pool_size: 100,
            max_idle_time_secs: 300, // 5分钟
            enabled: true,
        }
    }
}

/// 内存池中的对象条目
struct PoolEntry {
    /// 存储的对象
    object: Box<dyn Any + Send>,
    /// 最后访问时间
    last_access: Instant,
    /// 对象大小（字节）
    size: usize,
}

/// 通用内存池管理器
pub struct MemoryPool {
    /// 配置
    config: MemoryPoolConfig,
    /// 对象池 - 类型ID到对象列表的映射
    pools: Mutex<HashMap<String, Vec<PoolEntry>>>,
    /// 总内存使用量（字节）
    total_memory_usage: Mutex<usize>,
    /// 缓存命中统计
    hits: Mutex<usize>,
    /// 缓存未命中统计
    misses: Mutex<usize>,
}

impl MemoryPool {
    /// 创建新的内存池
    pub fn new(config: Option<MemoryPoolConfig>) -> Self {
        Self {
            config: config.unwrap_or_default(),
            pools: Mutex::new(HashMap::new()),
            total_memory_usage: Mutex::new(0),
            hits: Mutex::new(0),
            misses: Mutex::new(0),
        }
    }
    
    /// 从池中获取对象，如果没有则返回None
    pub fn get<T: 'static + Clone + Send>(&self, key: &str) -> Option<T> {
        if !self.config.enabled {
            return None;
        }
        
        let mut pools = self.pools.lock().unwrap();
        let pool = pools.get_mut(key)?;
        
        // 查找匹配类型的对象
        let index = pool.iter().position(|entry| {
            entry.object.downcast_ref::<T>().is_some()
        })?;
        
        // 从池中移除对象
        let entry = pool.remove(index);
        
        // 更新内存使用量
        let mut usage = self.total_memory_usage.lock().unwrap();
        *usage -= entry.size;
        
        // 更新命中计数
        let mut hits = self.hits.lock().unwrap();
        *hits += 1;
        
        // 返回对象的克隆
        entry.object.downcast_ref::<T>().map(|obj| obj.clone())
    }
    
    /// 将对象放回池中
    pub fn put<T: 'static + Clone + Send>(&self, key: &str, object: T, size: usize) {
        if !self.config.enabled {
            return;
        }
        
        let mut pools = self.pools.lock().unwrap();
        let pool = pools.entry(key.to_string()).or_insert_with(Vec::new);
        
        // 检查池大小
        if pool.len() >= self.config.max_pool_size {
            // 如果池已满，移除最旧的对象
            if let Some(oldest_idx) = pool.iter()
                .enumerate()
                .min_by_key(|(_, entry)| entry.last_access)
                .map(|(idx, _)| idx) {
                let removed = pool.remove(oldest_idx);
                let mut usage = self.total_memory_usage.lock().unwrap();
                *usage -= removed.size;
            }
        }
        
        // 添加新对象
        pool.push(PoolEntry {
            object: Box::new(object),
            last_access: Instant::now(),
            size,
        });
        
        // 更新内存使用量
        let mut usage = self.total_memory_usage.lock().unwrap();
        *usage += size;
    }
    
    /// 清理过期对象
    pub fn cleanup(&self) {
        if !self.config.enabled {
            return;
        }
        
        let now = Instant::now();
        let max_idle = Duration::from_secs(self.config.max_idle_time_secs);
        
        let mut pools = self.pools.lock().unwrap();
        let mut total_removed_size = 0;
        
        for pool in pools.values_mut() {
            let before_len = pool.len();
            
            // 移除过期对象
            pool.retain(|entry| {
                let retain = now.duration_since(entry.last_access) < max_idle;
                if !retain {
                    total_removed_size += entry.size;
                }
                retain
            });
            
            println!("Cleaned up {} objects from pool", before_len - pool.len());
        }
        
        // 更新内存使用量
        if total_removed_size > 0 {
            let mut usage = self.total_memory_usage.lock().unwrap();
            *usage -= total_removed_size;
            println!("Freed {} bytes from memory pool", total_removed_size);
        }
    }
    
    /// 获取内存使用统计
    pub fn get_stats(&self) -> MemoryPoolStats {
        let usage = *self.total_memory_usage.lock().unwrap();
        let hits = *self.hits.lock().unwrap();
        let misses = *self.misses.lock().unwrap();
        let hit_rate = if hits + misses > 0 {
            hits as f64 / (hits + misses) as f64
        } else {
            0.0
        };
        
        let mut pools = self.pools.lock().unwrap();
        let pool_count = pools.len();
        let object_count: usize = pools.values().map(|v| v.len()).sum();
        
        MemoryPoolStats {
            total_memory_usage: usage,
            pool_count,
            object_count,
            hit_count: hits,
            miss_count: misses,
            hit_rate,
        }
    }
    
    /// 完全清空内存池
    pub fn clear(&self) {
        let mut pools = self.pools.lock().unwrap();
        pools.clear();
        
        let mut usage = self.total_memory_usage.lock().unwrap();
        *usage = 0;
        
        println!("Memory pool cleared");
    }
}

/// 内存池统计信息
#[derive(Debug, Clone)]
pub struct MemoryPoolStats {
    /// 总内存使用量（字节）
    pub total_memory_usage: usize,
    /// 池数量
    pub pool_count: usize,
    /// 对象数量
    pub object_count: usize,
    /// 命中次数
    pub hit_count: usize,
    /// 未命中次数
    pub miss_count: usize,
    /// 命中率
    pub hit_rate: f64,
}

/// 全局内存池实例
lazy_static::lazy_static! {
    pub static ref GLOBAL_MEMORY_POOL: MemoryPool = MemoryPool::new(None);
}

/// 向量缓冲区，用于零拷贝数据传输
pub struct VectorBuffer<T: 'static + Clone + Send + Default> {
    /// 数据
    data: Vec<T>,
    /// 是否从池中获取
    from_pool: bool,
    /// 缓冲区键
    key: String,
}

impl<T: 'static + Clone + Send + Default> VectorBuffer<T> {
    /// 创建指定大小的缓冲区
    pub fn with_capacity(capacity: usize) -> Self {
        // 尝试从池中获取
        let key = format!("vector_buffer_{}", std::any::type_name::<T>());
        
        if let Some(mut buffer) = GLOBAL_MEMORY_POOL.get::<Vec<T>>(&key) {
            buffer.clear();
            if buffer.capacity() < capacity {
                buffer.reserve(capacity - buffer.capacity());
            }
            
            return Self {
                data: buffer,
                from_pool: true,
                key,
            };
        }
        
        // 如果池中没有，创建新的
        let mut misses = GLOBAL_MEMORY_POOL.misses.lock().unwrap();
        *misses += 1;
        
        Self {
            data: Vec::with_capacity(capacity),
            from_pool: false,
            key,
        }
    }
    
    /// 获取内部数据的可变引用
    pub fn as_mut(&mut self) -> &mut Vec<T> {
        &mut self.data
    }
    
    /// 获取内部数据的不可变引用
    pub fn as_ref(&self) -> &Vec<T> {
        &self.data
    }
    
    /// 获取内部数据的所有权
    pub fn into_inner(mut self) -> Vec<T> {
        std::mem::take(&mut self.data)
    }
}

impl<T: 'static + Clone + Send + Default> Drop for VectorBuffer<T> {
    fn drop(&mut self) {
        // 如果缓冲区是从池中获取的，或者容量足够大，则放回池中
        if self.from_pool || self.data.capacity() >= 1024 {
            let data = std::mem::take(&mut self.data);
            let size = data.capacity() * std::mem::size_of::<T>();
            GLOBAL_MEMORY_POOL.put(&self.key, data, size);
        }
    }
}

/// 缓存友好的数组结构
pub struct CacheAlignedArray<T> {
    /// 数据
    data: Vec<T>,
    /// 行大小
    row_size: usize,
    /// 行数
    rows: usize,
}

impl<T: Clone + Default> CacheAlignedArray<T> {
    /// 创建新的缓存对齐数组
    pub fn new(rows: usize, cols: usize) -> Self {
        // 计算缓存行大小对齐的列数
        let cache_line_size = 64; // 典型的缓存行大小
        let elem_size = std::mem::size_of::<T>();
        let elems_per_line = cache_line_size / elem_size;
        let padded_cols = ((cols + elems_per_line - 1) / elems_per_line) * elems_per_line;
        
        let mut data = Vec::with_capacity(rows * padded_cols);
        data.resize(rows * padded_cols, T::default());
        
        Self {
            data,
            row_size: padded_cols,
            rows,
        }
    }
    
    /// 从现有数据创建缓存对齐数组
    pub fn from_data(data: Vec<Vec<T>>) -> Self {
        let rows = data.len();
        if rows == 0 {
            return Self::new(0, 0);
        }
        
        let cols = data[0].len();
        let mut result = Self::new(rows, cols);
        
        for (i, row_data) in data.iter().enumerate() {
            for (j, val) in row_data.iter().enumerate() {
                if j < cols {
                    result.set(i, j, val.clone()).unwrap();
                }
            }
        }
        
        result
    }
    
    /// 创建预分配的缓存对齐数组，使用指定的初始值
    pub fn with_value(rows: usize, cols: usize, value: T) -> Self {
        // 计算缓存行大小对齐的列数
        let cache_line_size = 64; // 典型的缓存行大小
        let elem_size = std::mem::size_of::<T>();
        let elems_per_line = cache_line_size / elem_size;
        let padded_cols = ((cols + elems_per_line - 1) / elems_per_line) * elems_per_line;
        
        let mut data = Vec::with_capacity(rows * padded_cols);
        data.resize(rows * padded_cols, value);
        
        Self {
            data,
            row_size: padded_cols,
            rows,
        }
    }
    
    /// 获取元素
    pub fn get(&self, row: usize, col: usize) -> Option<&T> {
        if row >= self.rows || col >= self.row_size {
            return None;
        }
        
        Some(&self.data[row * self.row_size + col])
    }
    
    /// 获取可变元素
    pub fn get_mut(&mut self, row: usize, col: usize) -> Option<&mut T> {
        if row >= self.rows || col >= self.row_size {
            return None;
        }
        
        Some(&mut self.data[row * self.row_size + col])
    }
    
    /// 设置元素
    pub fn set(&mut self, row: usize, col: usize, value: T) -> Result<(), &'static str> {
        if row >= self.rows || col >= self.row_size {
            return Err("Index out of bounds");
        }
        
        self.data[row * self.row_size + col] = value;
        Ok(())
    }
    
    /// 获取行的切片
    pub fn row(&self, row: usize) -> Option<&[T]> {
        if row >= self.rows {
            return None;
        }
        
        let start = row * self.row_size;
        Some(&self.data[start..start + self.row_size])
    }
    
    /// 获取行的可变切片
    pub fn row_mut(&mut self, row: usize) -> Option<&mut [T]> {
        if row >= self.rows {
            return None;
        }
        
        let start = row * self.row_size;
        Some(&mut self.data[start..start + self.row_size])
    }
    
    /// 获取数组的行数
    pub fn num_rows(&self) -> usize {
        self.rows
    }
    
    /// 获取数组的列数（不包括填充）
    pub fn num_cols(&self) -> usize {
        if self.row_size == 0 {
            0
        } else {
            // 这里返回的是实际列数，不是填充后的列数
            self.row_size
        }
    }
    
    /// 将数组转换为普通的Vec<Vec<T>>
    pub fn to_vec(&self) -> Vec<Vec<T>> {
        let mut result = Vec::with_capacity(self.rows);
        for row in 0..self.rows {
            let row_data = self.row(row).unwrap();
            result.push(row_data.to_vec());
        }
        result
    }
    
    /// 重新调整数组大小
    pub fn resize(&mut self, new_rows: usize, new_cols: usize) {
        // 计算新的填充列数
        let cache_line_size = 64;
        let elem_size = std::mem::size_of::<T>();
        let elems_per_line = cache_line_size / elem_size;
        let new_padded_cols = ((new_cols + elems_per_line - 1) / elems_per_line) * elems_per_line;
        
        let mut new_data = Vec::with_capacity(new_rows * new_padded_cols);
        new_data.resize(new_rows * new_padded_cols, T::default());
        
        // 复制原有数据
        let min_rows = self.rows.min(new_rows);
        let min_cols = self.row_size.min(new_padded_cols);
        
        for row in 0..min_rows {
            for col in 0..min_cols {
                let old_idx = row * self.row_size + col;
                let new_idx = row * new_padded_cols + col;
                new_data[new_idx] = self.data[old_idx].clone();
            }
        }
        
        self.data = new_data;
        self.row_size = new_padded_cols;
        self.rows = new_rows;
    }
}

/// 线程安全的对象池，用于重用对象
pub struct ObjectPool<T> {
    /// 池中的对象
    pool: Mutex<Vec<T>>,
    /// 最大池大小
    max_size: usize,
}

impl<T> ObjectPool<T> {
    /// 创建新的对象池
    pub fn new(max_size: usize) -> Self {
        Self {
            pool: Mutex::new(Vec::with_capacity(max_size)),
            max_size,
        }
    }
    
    /// 从池中获取对象，如果池为空则使用提供的函数创建新对象
    pub fn get<F>(&self, create_fn: F) -> T
    where
        F: FnOnce() -> T,
    {
        let mut pool = self.pool.lock().unwrap();
        pool.pop().unwrap_or_else(create_fn)
    }
    
    /// 将对象归还池中
    pub fn put(&self, obj: T) {
        let mut pool = self.pool.lock().unwrap();
        if pool.len() < self.max_size {
            pool.push(obj);
        }
    }
    
    /// 获取当前池中对象数量
    pub fn size(&self) -> usize {
        self.pool.lock().unwrap().len()
    }
    
    /// 清空对象池
    pub fn clear(&self) {
        self.pool.lock().unwrap().clear();
    }
}

/// 带有生命周期的池化对象包装器
pub struct PooledObject<'a, T> {
    /// 对象
    obj: Option<T>,
    /// 对象池引用
    pool: &'a ObjectPool<T>,
}

impl<'a, T> PooledObject<'a, T> {
    /// 创建新的池化对象
    pub fn new(obj: T, pool: &'a ObjectPool<T>) -> Self {
        Self {
            obj: Some(obj),
            pool,
        }
    }
    
    /// 获取对象的不可变引用
    pub fn get(&self) -> &T {
        self.obj.as_ref().unwrap()
    }
    
    /// 获取对象的可变引用
    pub fn get_mut(&mut self) -> &mut T {
        self.obj.as_mut().unwrap()
    }
}

impl<'a, T> Drop for PooledObject<'a, T> {
    fn drop(&mut self) {
        if let Some(obj) = self.obj.take() {
            self.pool.put(obj);
        }
    }
}

/// 内存预分配器，用于批量预分配内存
pub struct MemoryPreallocator {
    /// 预分配的内存块
    blocks: Mutex<HashMap<String, Vec<Vec<u8>>>>,
    /// 每个块的大小
    block_size: usize,
    /// 每种类型预分配的块数
    blocks_per_type: usize,
}

impl MemoryPreallocator {
    /// 创建新的内存预分配器
    pub fn new(block_size: usize, blocks_per_type: usize) -> Self {
        Self {
            blocks: Mutex::new(HashMap::new()),
            block_size,
            blocks_per_type,
        }
    }
    
    /// 预分配指定类型的内存
    pub fn preallocate(&self, type_name: &str) {
        let mut blocks = self.blocks.lock().unwrap();
        let type_blocks = blocks.entry(type_name.to_string()).or_insert_with(Vec::new);
        
        // 如果已经预分配了足够的块，则不再分配
        if type_blocks.len() >= self.blocks_per_type {
            return;
        }
        
        // 预分配新的块
        let to_allocate = self.blocks_per_type - type_blocks.len();
        for _ in 0..to_allocate {
            let mut block = Vec::with_capacity(self.block_size);
            // 实际分配内存
            block.resize(self.block_size, 0);
            type_blocks.push(block);
        }
        
        println!("Preallocated {} memory blocks for type {}", to_allocate, type_name);
    }
    
    /// 获取预分配的内存块
    pub fn get_block(&self, type_name: &str) -> Option<Vec<u8>> {
        let mut blocks = self.blocks.lock().unwrap();
        if let Some(type_blocks) = blocks.get_mut(type_name) {
            type_blocks.pop()
        } else {
            None
        }
    }
    
    /// 归还内存块
    pub fn return_block(&self, type_name: &str, block: Vec<u8>) {
        let mut blocks = self.blocks.lock().unwrap();
        let type_blocks = blocks.entry(type_name.to_string()).or_insert_with(Vec::new);
        
        if type_blocks.len() < self.blocks_per_type {
            type_blocks.push(block);
        }
    }
    
    /// 获取统计信息
    pub fn get_stats(&self) -> HashMap<String, usize> {
        let blocks = self.blocks.lock().unwrap();
        blocks.iter().map(|(k, v)| (k.clone(), v.len())).collect()
    }
}

/// 全局内存预分配器实例
lazy_static::lazy_static! {
    pub static ref GLOBAL_MEMORY_PREALLOCATOR: MemoryPreallocator = MemoryPreallocator::new(4096, 10);
}